from eventlet.queue import Queue
from collections import defaultdict
from typing import Dict
import os,time

class Pool:
    '''
        封装Local对象  资源独享 让出socket读权限 后面可以继续改善可读性 防止os。fork进程拷贝对象  导致错误的访问scoket资源  
    '''
    _pool = dict()

    # def __init__(self):

    #     self._pool = dict()

    def __setitem__(self, key, value):
        if self.id not in self._pool:
            self._pool[self.id] = dict()
        if key in self._pool[self.id]:
            assert self._pool[self.id][key].qsize() == 0 ,'queue size is empty, it maybe throw error'
            self._pool[self.id][key].put(value)
        else:
            self._pool[self.id][key] = Queue(maxsize=1)
            self._pool[self.id][key].put(value)

    def __getitem__(self, key):
        queue = self._pool[self.id][key]
        return queue.get()

    def __delitem__(self, key):
        del self._pool[self.id][key]

    def keys(self):
        res = []
        for i in self._pool:
            res.extend(self._pool[i].keys())
        return res




    def size(self, key):
        return self._pool[self.id][key].qsize()
        
    def close(self,key):
        for i in self._pool:
            if key in self._pool[i]:
                conn = self._pool[self.id][key].get()
                conn.close()
                self._pool[i][key].put(conn)

    @property
    def id(self):
        return os.getpid()

        
    def __str__(self):
        return str(self._pool)